'use strict';
const Controller = require('egg').Controller;
const fes = require('fs-extra');
const path = require('path');
class TestController extends Controller {

  //todo  文件上传
  async index(){
    const { ctx } = this;
    console.log(ctx.request);
    const file = ctx.request.files[0];
    console.log(file);
    const {name,hash} = ctx.request.body;
    console.log(name);
    const chunkPath = path.resolve(this.config.UPLOAD__FILE,hash);
    if(fes.existsSync(chunkPath)){
      fes.mkdir(chunkPath);
    }
    // TODO 这是将前台传递的文件放到publice文件夹下
    await fes.move(file.filepath,`${chunkPath}/${name}`);
    ctx.body = '上传成功'
  }
  //合并文件（切片上传的文件）
  async merg(){
    const {ctx} = this;
    const {ext,size,hash} = ctx.request.body;
    const filePath = path.resolve(this.config.UPLOAD__FILE,`${hash}.${ext}`);
    const res = await ctx.service.tools.merg(filePath,hash,size);
    ctx.body={
      res,
      title:'上传文件合并成功',
      url:`public/${hash}.${ext}`
    }
  }

  // todo 妙传和断点续传的实现
  async checkFile(){
    const {ctx} = this;
    const {ext,hash} = ctx.request.body;
    const filePath = path.resolve(this.config.UPLOAD__FILE,`${hash}.${ext}`);

    let upload = false;
    let uploadList = [];
    if(fes.existsSync(filePath)){
      upload = true;
    }else{//todo 读取文件目录下是否有这个文件
      uploadList = await this.getUploadList(path.resolve(this.config.UPLOAD__FILE,hash));
    }
    ctx.body={
      upload,
      uploadList
    }
  }
  async getUploadList(dir){
    return fes.existsSync(dir)
        ?(await fes.readdir(dir)).filter(name=>name[0]!='.')
        :[]
  }
}

module.exports = TestController;
